--- monadic list functions stack overflow early
--- This program should run without @-Xss@ or @-Xmx@ settings on a 64bit JVM.
module tests.comp.Issue67 where


import frege.Prelude as P 

{-
chunked !n [] = []
chunked !n xs = take n xs : chunked n (drop n xs)

unsafeSequence = foldr (liftM2 (:)) (return [])

sequence = fold (liftM2 (++)) (return []) . map unsafeSequence . chunked 512
-- sequence' = liftM concat . map unsafeSequence . chunked 512 

filterM mp = fold (liftM2 (++)) (return []) . map (P.filterM mp) . chunked 512

foldM p z = fold (\acc\as -> acc >>= flip (P.foldM p) as) (return z)  . chunked 512

sequence_ [] = return ()
sequence_ (x:xs) = x >> sequence_ xs

-}       

many  = [1L..100_000]
manym = map Just many
manyio = println "a" : replicate 19998 (print "") ++ [println "z"]

main = do
    -- forever (println "a")
    sequence_ manyio
    println 'A' >> replicateM_ 99998 (print "") >> println 'Z'
    println 'A' >> replicateM  99998 (print "") >> println 'Z'
    println $ fmap (take 20) (sequence manym) 
    println (fmap length . filterM (Just . even) $ many)
    println (foldM (\a b -> Just $! (a+b)) 0 many) 
